package com.work.common.core.webscoket;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.beust.jcommander.internal.Lists;
import com.beust.jcommander.internal.Maps;
import com.work.common.constant.Constants;
import com.work.common.core.redis.RedisCache;
import com.work.common.utils.StringUtils;
import com.work.common.utils.spring.SpringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

@Component
@Slf4j
@ServerEndpoint("/api/websocket/{userId}")
public class WebSocketServerImpl {

    /**
     * 静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
     */
    private static int onlineCount = 0;
    /**
     * concurrent包的线程安全Set，用来存放每个客户端对应的WebSocket对象。
     */
    public static ConcurrentHashMap<String, WebSocketServerImpl> webSocketMap = new ConcurrentHashMap<>();
    /**
     * 与某个客户端的连接会话，需要通过它来给客户端发送数据
     */
    private Session session;
    /**
     * 接收userId
     */
    private String userId = "";

    private final static RedisCache redisCache = SpringUtils.getBean(RedisCache.class);

    /**
     * 连接建立成
     * 功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId) {
        this.session = session;
        this.userId = userId;
        if (webSocketMap.containsKey(userId)) {
            webSocketMap.remove(userId);
            //加入set中
            webSocketMap.put(userId, this);
        } else {
            //加入set中
            webSocketMap.put(userId, this);
            //在线数加1
            addOnlineCount();
        }
        log.info("用户连接:" + userId + ",当前在线人数为:" + getOnlineCount());
        sendMessage("用户连接:" + userId + "连接成功");
        sendInfo(userId);

    }


    private void sendInfo(String userId) {
        Long expire = redisCache.getExpire(Constants.WORK_ORDER_WEBSOCKET_MESSAGE + userId);
        if (expire > -2) {
            List<Map<String, Object>> dataList = redisCache.getCacheList(Constants.WORK_ORDER_WEBSOCKET_MESSAGE + userId);
            int total = 0;
            List<Object> dataDtoList = Lists.newArrayList();
            Map<String, Object> map = Maps.newHashMap();
            for (Map<String, Object> dtoMap : dataList) {
                Object message = dtoMap.get("message");

                if (Objects.nonNull(message)) {
                    JSONObject parse = (JSONObject) JSON.parse(((String) message));
                    JSONArray data = (JSONArray) parse.get("data");
                    JSONObject o = (JSONObject) data.get(0);
                    Integer nums = (Integer) o.get("total");
                    dataDtoList.add(o);

                    total = total + nums;
                }
            }
            map.put("total", total);
            map.put("data", dataDtoList);
            if (!Objects.equals(0, total)) {
                sendInfo(JSON.toJSONString(map), userId, null);
            }


        }
    }

    /**
     * 连接关闭
     * 调用的方法
     */
    @OnClose
    public void onClose() {
        if (webSocketMap.containsKey(userId)) {
            webSocketMap.remove(userId);
            //从set中删除
            subOnlineCount();
        }
        log.info("用户退出:" + userId + ",当前在线人数为:" + getOnlineCount());
    }

    /**
     * 收到客户端消
     * 息后调用的方法
     *
     * @param message 客户端发送过来的消息
     **/
    @OnMessage
    public void onMessage(String message, Session session) {
        //可以群发消息 消息可保存到数据库、redis
        if (StringUtils.isNotBlank(message)) {
            try {
                if (StringUtils.isNotEmpty(userId) && Objects.nonNull(webSocketMap.get(userId))) {
                    webSocketMap.get(userId).sendMessage("tong");

                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {

        log.error("用户错误:" + this.userId + ",原因:" + error.getMessage());
        error.printStackTrace();
    }

    /**
     * 实现服务
     * 器主动推送
     */
    public void sendMessage(String message) {
        try {
            synchronized (session) {
                this.session.getBasicRemote().sendText(message);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 发送自定
     * 义消息
     **/
    public static void sendInfo(String message, String userId, String orderNo) {

        String key = Constants.WORK_ORDER_WEBSOCKET_MESSAGE + userId;
        Long expire = redisCache.getExpire(key);
        if (expire > -2) {
            List<Map<String, Object>> dataList = redisCache.getCacheList(key);
            redisCache.deleteObject(key);
            for (Map<String, Object> dtoMap : dataList) {
                String dtoOrderNo = (String) dtoMap.get("orderNo");
                if (Objects.equals(orderNo, dtoOrderNo)) {
                    dtoMap.put("userId", userId);
                    dtoMap.put("message", message);
                }
            }
            redisCache.setCacheList(key, dataList);
        }

        if (StringUtils.isNotBlank(userId) && webSocketMap.containsKey(userId)) {
            log.info("发送在线消息到:" + userId + "，报文:" + message);
            webSocketMap.get(userId).sendMessage(message);
        } else {
//            log.error("用户"+userId+",不在线！");

        }

    }

    /**
     * 获得此时的
     * 在线人数
     *
     * @return
     */
    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    /**
     * 在线人
     * 数加1
     */
    public static synchronized void addOnlineCount() {
        WebSocketServerImpl.onlineCount++;
    }

    /**
     * 在线人
     * 数减1
     */
    public static synchronized void subOnlineCount() {
        WebSocketServerImpl.onlineCount--;
    }

}
